package com.my.lucky.service;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.my.lucky.config.IwencaiConfig;
import com.my.lucky.entity.StockQueryRecord;
import com.my.lucky.entity.WencaiKeyword;
import com.my.lucky.model.MonitorResponse;
import com.my.lucky.model.Stock2;
import com.my.lucky.repository.StockQueryRecordRepository;
import com.my.lucky.util.RankListCacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class StockMonitorService {
    @Autowired
    StockQueryRecordRepository stockQueryRecordRepository;
    @Autowired
    RankListCacheUtil rankListCacheUtil;
    @Autowired
    private IwencaiConfig iwencaiConfig;
    @Autowired
    private IWencaiServiceTools iwencaiService;
    @Autowired
    private StockAlertService alertService;
    @Autowired
    private WencaiKeywordService wencaiKeywordService;

    public MonitorResponse monitor(String focusStocks, String iwencaiKeyword) {
        log.info("关注的股票: {}", focusStocks);

        // 验证股票代码格式
        if (focusStocks != null && !focusStocks.trim().isEmpty()) {
//            boolean hasInvalidCode = Arrays.stream(focusStocks.split("\n"))
            boolean hasInvalidCode = Arrays.stream(focusStocks.split("\n|,"))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .anyMatch(code -> !code.matches("\\d{6}"));

            if (hasInvalidCode) {
                throw new IllegalArgumentException("股票代码格式错误，必须是6位数字");
            }
        }

        // 保存或获取问财关键词
        WencaiKeyword keyword = wencaiKeywordService.getOrCreateKeyword(iwencaiKeyword);

        // 获取问财搜索结果
        List<Map<String, Object>> maps = iwencaiService.searchStocks(iwencaiKeyword, iwencaiConfig.getIsLocal());

        // 如果问财没有返回结果，直接返回空结果
        if (maps.isEmpty()) {
            return new MonitorResponse(new ArrayList<>(), 0, new ArrayList<>());
        }

//        Map<String, StockHotRank> rankListTodayMap = rankListCacheUtil.getRankListToday().stream()
//                .collect(Collectors.toMap(StockHotRank::getStockCode, rank -> rank));
//        Map<String, StockHotRank> rankListYestMap = rankListCacheUtil.getRankListYest().stream()
//                .collect(Collectors.toMap(StockHotRank::getStockCode, rank -> rank));
//        Map<String, StockHotRank> rankListBeforMap = rankListCacheUtil.getRankListBefor().stream()
//                .collect(Collectors.toMap(StockHotRank::getStockCode, rank -> rank));
        // 将 maps 转换为 Stock2 对象列表
        List<Stock2> iwencaiStocks = maps.stream()
                .map(map -> {
                    Stock2 stock = new Stock2();
                    stock.setCode((String) map.get("code"));
                    stock.setName((String) map.get("name"));
                    stock.setPrice(String.valueOf(map.get("price")));
                    stock.setChangePercent(map.get("changePercent") != null ?
                            Double.parseDouble(String.valueOf(map.get("changePercent"))) : null);
                    stock.setOpen(String.valueOf(map.get("open")));
                    stock.setHigh(String.valueOf(map.get("high")));
                    stock.setLow(String.valueOf(map.get("low")));
                    stock.setFlow(map.get("flow") != null ? Long.parseLong(map.get("flow").toString()) : null);
                    stock.setGainian(String.valueOf(map.get("gainian")));

                    stock.setMainCapitalFlow(map.get("mainCapitalFlow") != null ?
                            BigDecimal.valueOf(Double.parseDouble(String.valueOf(map.get("mainCapitalFlow")))) : null);

                    stock.setCapitalFlow(map.get("capitalFlow") != null ?
                            BigDecimal.valueOf(Double.parseDouble(String.valueOf(map.get("capitalFlow")))) : null);
                    String ranks = "[%s,%s,%s]";

//                    StockHotRank stockHotRankbefor = rankListBeforMap.get(stock.getCode());
//                    StockHotRank stockHotRankyest = rankListYestMap.get(stock.getCode());
//                    StockHotRank stockHotRanktoday = rankListTodayMap.get(stock.getCode());
//
//                    stock.setHots(String.format(ranks, stockHotRankbefor == null ? "-" : stockHotRankbefor.getRankPosition() + ""
//                            , stockHotRankyest == null ? "-" : stockHotRankyest.getRankPosition() + ""
//                            , stockHotRanktoday == null ? "-" : stockHotRanktoday.getRankPosition() + ""

//                    stockMap.put("rank_position", stock.getLong("个股热度排名" + yyyyMMdd));
//                    stockMap.put("old_rank_position", stock.getLong("个股热度排名" + yesterdayyyyyMMdd));

                    Long rank_position = (Long) map.get("rank_position");
                    Long old_rank_position = (Long) map.get("old_rank_position");
                    stock.setRankPosition(rank_position);
                    stock.setOldRankPosition(old_rank_position);

                    long oldRank = old_rank_position != null ? old_rank_position.longValue() : 9999L;
                    long rank = rank_position != null ? rank_position.longValue() : 9999L;

                    stock.setHots(String.format(ranks, rank
                            , oldRank
                            , (oldRank - rank) + ""
                    ));
                    stock.setFlows(stock.getFlow() != null ?
                            (stock.getFlow() >= 100000000 ?
                                    String.format("%.2f亿", stock.getFlow() / 100000000.0) :
                                    String.format("%.2f万", stock.getFlow() / 10000.0)) :
                            "-");
                    return stock;
                })
                .collect(Collectors.toList());
        List<Map<String, Object>> maps1 = iwencaiService.cacheGainian;
        List<String> names = maps1.stream().map(e -> e.get("name").toString()).collect(Collectors.toList());
        iwencaiStocks.forEach(e -> {
            if (StrUtil.isNotBlank(e.getGainian())) {
                boolean isCon = false;
                String gainian = e.getGainian();
                StringBuffer gg = new StringBuffer();
                for (String name : names) {
                    if (e.getGainian().contains(name)) {
                        gg.append(name + ",");

                        isCon = true;
                        // break;
                    }
                }

                if (!isCon) {
                    e.setGainian("");
                } else {
                    e.setGainian(gg.substring(0, gg.length() - 1));
                }

                Set<String> allgainians = Arrays.stream(gainian.split(";"))
                        .collect(Collectors.toSet());
                Set<String> newgainians = Arrays.stream(e.getGainian().split(","))
                        .collect(Collectors.toSet());

                String notgainian = (allgainians == null || newgainians == null) ? "" :
                        allgainians.stream()
                                .filter(item -> !newgainians.contains(item))
                                .collect(Collectors.joining(","));
                e.setNoHotgainian(notgainian);
            }
        });
        // 解析关注的股票代码
        Set<String> focusStockSet = Arrays.stream(focusStocks.split("\n"))
                .map(String::trim)
                .filter(s -> !s.isEmpty())  // 过滤掉空行
                .collect(Collectors.toSet());

        // 筛选出同时在问财结果和关注列表中的股票
        List<Stock2> matchedStocks = iwencaiStocks.stream()
                .filter(stock -> focusStockSet.contains(stock.getCode().substring(0, 6)))
                .collect(Collectors.toList());

        // 生成提示信息
        List<Stock2> alerts = alertService.generateAlerts(iwencaiStocks, focusStockSet, keyword);
        // 合并alerts和matchedStocks，根据股票代码去重，保留alerts中的记录
//        List<Stock2> mergedList = new ArrayList<>(alerts);
//        Set<String> alertCodes = alerts.stream()
//                .map(stock -> stock.getCode().substring(0, 6))
//                .collect(Collectors.toSet());

//        iwencaiStocks.stream()
//                .filter(stock -> !alertCodes.contains(stock.getCode().substring(0, 6)))
//                .forEach(mergedList::add);
        LocalDateTime now = LocalDateTime.now();
        log.info("本次查询获取条数: {}", alerts.size());
        ThreadUtil.execAsync(() -> {
            // 保存查询记录到数据库
            try {

                List<StockQueryRecord> nowTodayDrecords = iwencaiConfig.getNowTodayDrecords();
                for (Stock2 stock : alerts) {
                    StockQueryRecord record = new StockQueryRecord();
                    record.setWencaiKeyword(keyword);
                    record.setStockCode(stock.getCode().substring(0, 6));
                    record.setStockName(stock.getName());
                    record.setType(stock.getType() == null ? 0 : stock.getType());
                    record.setCreateTime(now);
                    record.setQueryTime(now);
                    record.setChangePercent(stock.getChangePercent());
                    record.setFlow(stock.getFlow());
                    record.setGainian(stock.getGainian());
                    record.setAllGainian(stock.getNoHotgainian() + "," + stock.getGainian());
                    record.setHigh(stock.getHigh());
                    record.setLow(stock.getLow());
                    record.setPrice(stock.getPrice());
                    record.setOpen(stock.getOpen());
                    record.setRankPosition(stock.getRankPosition());
                    record.setOldRankPosition(stock.getOldRankPosition());
                    record.setMainCapitalFlow(stock.getMainCapitalFlow());
                    record.setCapitalFlow(stock.getCapitalFlow());
                    stockQueryRecordRepository.save(record);
                    stockQueryRecordRepository.updateByqueryTimeAfterToday(record.getRankPosition(), record.getOldRankPosition(), record.getStockCode());

                    if(nowTodayDrecords==null){
                        nowTodayDrecords = new ArrayList<>();
                    }
                    nowTodayDrecords.add(record);
                    iwencaiConfig.setNowTodayDrecords(nowTodayDrecords);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //   log.info("钉钉提醒: {}", JSONUtil.toJsonStr(alerts));
        });

        return new MonitorResponse(alerts, matchedStocks.size(), iwencaiService.cacheGainian);
    }
} 